<script setup lang="ts">
  import { addPatientAPI, patientDetailAPI, updatePatientAPI } from '@/api/patient'
  import type { PatientItem } from '@/type/patient'
  import { onLoad } from '@dcloudio/uni-app'
  import { ref } from 'vue'
  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })
  // 1. 表单数据
  const formData = ref({
    name: '',
    idCard: '121126200002082593',
    gender: 1,
    defaultFlag: 1,
  })
  const formRef = ref<UniHelper.UniFormsInstance>()
  const onSubmit = async () => {
    try {
      await formRef.value?.validate!()
      if (xxxId.value) {
        await updatePatientAPI({ id: xxxId.value, ...formData.value } as PatientItem)
      } else {
        await addPatientAPI(formData.value)
      }
      uni.showToast({
        title: !xxxId.value ? '保存成功' : '编辑成功',
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    } catch (error) {
      console.log('error  ----->  ', error)
    }
  }
  const formRules: UniHelper.UniFormsRules = {
    name: {
      rules: [
        { required: true, errorMessage: '请输入患者姓名' },
        { pattern: /^[\u4e00-\u9fa5]{2,5}$/, errorMessage: '患者姓名必须2-5位中文' },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: '请输入患者身份证号码' },
        {
          pattern:
            /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}[0-9Xx]$/,
          errorMessage: '患者身份证号码不正确',
        },
      ],
    },
    gender: {
      rules: [
        {
          validateFunction: (rule, value, data, callback) => {
            // 获取身份证号第17位
            const idCard17th = data.idCard?.charAt(16)
            if (!idCard17th) return callback('请先填写身份证号')
            // 判断性别是否匹配
            const isMale = value === 1
            const isIdCardMale = parseInt(idCard17th) % 2 === 1
            if (isMale !== isIdCardMale) {
              return callback('性别与身份证号不匹配')
            }
            callback()
          },
        },
      ],
    },
  }

  const xxxId = ref<string>('')
  onLoad(async (params) => {
    if (params?.id) {
      xxxId.value = params.id
      uni.setNavigationBarTitle({ title: '编辑患者' })
      const res = await patientDetailAPI(xxxId.value)
      formData.value = {
        name: res.name,
        idCard: res.idCard,
        gender: res.gender!,
        defaultFlag: res.defaultFlag,
      }
    }
  })
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="formRef" :model="formData" :rules="formRules">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :style="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :style="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            mode="tag"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="defaultFlag">
          <view class="uni-switch">
            <switch
              :checked="!!formData.defaultFlag"
              @change="formData.defaultFlag = $event.detail.value ? 1 : 0"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import './form.scss';
</style>
